import pymongo
import csv


# 把表中的内容读取到data中,data是二维数组
def read_csv_except_first_row_csv():
    # 使用原始字符串表示路径
    file_path = r'../../../data/outer/import_file.csv'
    data = []
    with open(file_path, 'r', newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        next(reader)  # 跳过第一行
        for row in reader:
            data.append(row)
    return data
def import_csv():
    # 完成表的创建 , 表单名称为 collection
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client["ACM_MEMBER"]
    collection = db["OUT_TEAM_INFORMATION"]

    data = read_csv_except_first_row_csv()

    # `学号 , 姓名 , 牛客账号 , 洛谷账号 , codeforces账号 , atcoder账号 , vjudge账号
    # `密码 ,性别 , 年级 , 所属学院 , 专业 ,  `
    for row in data :
        if len(row) == 0 :
            break
        student_id =  row[0]
        name = row[1]
        nc_id = row[2]
        lg_id = row[3]
        cf_id = row[4]
        at_id = row[5]
        vj_id = row[6]
        can_insert = collection.find_one({"student_id": student_id})
        if can_insert :
            need_update = False
            if can_insert['nowcoder_id'] != nc_id :
                need_update = True
            if can_insert['luogu_id'] != lg_id :
                need_update = True
            if can_insert['codeforces_id'] != cf_id :
                need_update = True
            if can_insert['atcoder_id'] != at_id :
                need_update = True
            if can_insert['vjudge_id'] != vj_id :
                need_update = True
            if can_insert['name'] != name :
                need_update = True
            if need_update :
                new_values = {"$set": {
                    "name": name,
                    "nowcoder_id": nc_id,
                    "luogu_id": lg_id,
                    "codeforces_id": cf_id,
                    "atcoder_id": at_id,
                    "vjudge_id": vj_id,
                }}
                collection.update_one({"student_id": student_id}, new_values)
                print(student_id + "更新成功")
            else :
                print(student_id + "已经存在")
            continue
        else :
            collection.insert_one({
                "student_id": student_id,
                "name": name,
                "nowcoder_id": nc_id,
                "luogu_id": lg_id,
                "codeforces_id": cf_id,
                "atcoder_id": at_id,
                "vjudge_id": vj_id,
            })
            print(student_id + "插入成功")
    client.close()

if __name__ == '__main__':
    import_csv()

